<template>
  <div class="w-full h-full">
    <div class="flex h-full">
      <WorkflowMenu
        class="bg-[#f5f6f7] min-w-[140px] rounded-tl-xl pt-16"
        :menuItem="[...menuItem]"
        :menuGap="reactiveItemState.menuGap"
        :menuHeight="reactiveItemState.menuHeight"
        @operation-callback="handleOperation"
      >
        <AButton
          class="bg-[#001428] text-[#FFFFFF] text-[15px] w-full max-w-96"
          type="primary"
          :disabled="currContent.disabledUseMoFang"
          @click.stop="handleCreativeMoFang"
        >
          <template #icon
            ><img :src="MoFang" class="inline-block w-[18px] h-[15px] mt-[-2px]" /></template
          >创意魔方</AButton
        >
      </WorkflowMenu>
      <div v-if="showContent" class="flex-1 flex flex-col min-w-0 pt-12 mx-4">
        <div class="h-4">
          <p v-if="currContent.task" class="text-[#5f52a0] text-[11px] text-right italic">
            销量:{{ currContent.task?.item_saleCon ?? 0 }}&nbsp;&nbsp;到手佣金:{{
              currContent.task?.item_brokerage ?? 0
            }}
          </p>
        </div>
        <WorkflowEditor
          class="flex-1"
          :menuItem="[...menuItem]"
          :menuGap="reactiveItemState.menuGap"
          :menuHeight="reactiveItemState.menuHeight"
          @input-callback="handleInput"
          @input-click-callback="handleInputClick"
          @input-keydown-callback="handleInputKeydown"
        >
          <template #subBtn
            ><AButton
              class="bg-[#001428] text-[#FFFFFF] text-[15px] w-full max-w-96"
              type="primary"
              :loading="loadingCreateDraft"
              :disabled="!useCreateDraftBtn"
              @click="handleCreateDraft"
            >
              <template #icon
                ><img :src="JianYing" class="inline-block w-[18px] h-[15px] mt-[-2px]" /></template
              >创建草稿</AButton
            ></template
          >
        </WorkflowEditor>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  createDraftApi,
  creativeMoFangApi,
  productSellcopyRefreshApi
} from '@main/service/workflow';
import ProductTitle from '@main/assets/images/workflow/product-title.webp';
import ProductName from '@main/assets/images/workflow/product-name.webp';
import SellPointCore from '@main/assets/images/workflow/sell-point-core.webp';
import SellPointCoreOverride from '@main/assets/images/workflow/sell-point-core-override.webp';
import VideoText from '@main/assets/images/workflow/video-text.webp';
import VideoTextOverride from '@main/assets/images/workflow/video-text-override.webp';
import VideoName from '@main/assets/images/workflow/video-name.webp';
import VideoNameOverride from '@main/assets/images/workflow/video-name-override.webp';
import VideoMaterail from '@main/assets/images/workflow/video-materail.webp';
import JianYing from '@main/assets/images/workflow/jianying.webp';
import MoFang from '@main/assets/images/workflow/mofang.webp';
import Video from '@shared/assets/images/video.webp';
import WorkflowMenu from './components/Menu/MenuWrap.vue';
import WorkflowEditor from './components/Editor/Editor.vue';
import { router } from '@main/router';
import { copyTextToClipboard } from '@shared/hooks/web/useCopyToClipboard';
import { writeFile, getFile, getVideoMeta } from '@main/utils/fs';
import { useWorkflowStore } from '@main/store/workflow';
import { useAppStore } from '@shared/store/app';
import { ref, computed } from 'vue';
import { reactiveComputed } from '@vueuse/core';
import { message } from 'ant-design-vue';
import { findIndex } from 'lodash-es';
import type { createDraftReq } from '@/view/main/service/workflow/type';
import type { WorkflowInputProperties, WorkflowMenuItemProperties } from './types/menu-item';
import type { ChangeEvent } from 'ant-design-vue/es/_util/EventInterface';

const appStore = useAppStore();
const workflowStore = useWorkflowStore();

const currContent = computed(
  () =>
    workflowStore.getTaskContent.value ??
    workflowStore.getMyContent.value ??
    workflowStore.getInitContent
);

const draftDirectoryProduction = computed(() => workflowStore.getDraftDirectory + '-生产');

const useCreateDraftBtn = computed(() => currContent.value.product_id);
const showContent = computed(() => !appStore.hideContent);
const loadingCreateDraft = ref(false);
const loadingCreativeMoFang = ref(false);
//草稿文件
const fileName_content = 'draft_content.json',
  fileName_meta = 'draft_meta_info.json';
//行高 行间距
const reactiveItemState = {
  menuGap: 15,
  menuHeight: 32
};

let isOpen = false;
const handleInputClick = async (menu: WorkflowMenuItemProperties) => {
  if (isOpen) return;

  isOpen = true;
  if(menu.title == '视频素材' && currContent.value.product_id) {
    currContent.value.video_materials = await window.clientAppSdk.ipc.ipcRenderer.invoke('rc:select-videos');
  }

  if(menu.title == '商品标题' && currContent.value.id == '') {
    workflowStore.addContentAction('');
  }

  isOpen = false;
};

const handleInputKeydown = async (e: KeyboardEvent, menu: WorkflowMenuItemProperties) => {
  if (menu.title == '视频名称') {
    if (!currContent.value.is_deepAi_override || menu.inputArray.length >= 5) return;
    if (e.key === 'Enter') {
      let newVideoNames =
        (currContent.value.is_deepAi_override
          ? currContent.value.video_names_override
          : currContent.value.video_names) ?? [];

      workflowStore.setContentAction({
        ...currContent.value,
        video_names_override: [...newVideoNames, '']
      });
    }
  }
  if(menu.title == '商品标题') {
    if(e.ctrlKey && e.key == 'Enter' && !currContent.value.task){
      if(!currContent.value.product_title) {
        message.warning('商品标题不能为空');
        return;
      }
      console.log('kd商品标题', (e.target as (HTMLInputElement | HTMLTextAreaElement)).value);
      workflowStore.addContentAction((e.target as (HTMLInputElement | HTMLTextAreaElement)).value);
    }
  }
};

const handleInput = (event: ChangeEvent,input: WorkflowInputProperties, menu: WorkflowMenuItemProperties) => {
  if(currContent.value.id == '') {
    event.preventDefault();
    return;
  }
  if (menu.title == '商品标题')
      workflowStore.setContentAction({
        ...currContent.value,
        product_title: input.content
      });

  if (menu.title == '商品名称') currContent.value.product_name = input.content;
  if (menu.title == '核心卖点') {
    let newObj = {
      sell_point_override: currContent.value.sell_point_override,
      sell_point: currContent.value.sell_point
    };
    if (currContent.value.is_sell_point_override) newObj.sell_point_override = input.content;
    else newObj.sell_point = input.content;
    workflowStore.setContentAction({
      ...currContent.value,
      ...newObj
    });
  }
  if (menu.title == '视频文案') {
    let newObj = {
      sell_copy_override: currContent.value.sell_copy_override,
      sell_copy: currContent.value.sell_copy
    };
    if (currContent.value.is_deepAi_override) newObj.sell_copy_override = input.content;
    else newObj.sell_copy = input.content;
    workflowStore.setContentAction({
      ...currContent.value,
      ...newObj
    });
  }
  if (menu.title == '视频名称') {
    const index = findIndex(menu.inputArray, input);
    if (index === -1) {
      return;
    }
    workflowStore.setContentAction({
      ...currContent.value,
      ...(() => {
        let newObj = {
          video_names_override: currContent.value.video_names_override,
          video_names: currContent.value.video_names
        };
        if (currContent.value.is_deepAi_override) {
          newObj.video_names_override = [
            ...(newObj.video_names_override ?? []).slice(0, index),
            input.content,
            ...(newObj.video_names_override ?? []).slice(index + 1)
          ];
        } else {
          newObj.video_names = [
            ...(newObj.video_names ?? []).slice(0, index),
            input.content,
            ...(newObj.video_names ?? []).slice(index + 1)
          ];
        }
        return newObj;
      })()
    });
  }
};

//创建生产草稿
const handleCreateDraft = async () => {
  if (!currContent.value.product_title) {
    message.warning('商品标题不能为空');
    return;
  }

  if (!currContent.value.product_name) {
    message.warning('商品名称不能为空');
    return;
  }

  if (
    (currContent.value.is_sell_point_override && !currContent.value.sell_point_override) ||
    (!currContent.value.is_sell_point_override && !currContent.value.sell_point)
  ) {
    message.warning('核心卖点不能为空');
    return;
  }

  if (!currContent.value.video_materials || currContent.value.video_materials.length == 0) {
    message.warning('请选择视频素材');
    return;
  }

  if (!workflowStore.getDraftDirectory) {
    message.warning('请在左下角设置-目录设置->设置剪映草稿目录');
    return;
  }

  if (!workflowStore.getMaterialDirectory) {
    message.warning('请在左下角设置-目录设置->设置视频素材下载目录');
    return;
  }

  let file_content: any = null,
    file_meta: any = null;
  loadingCreateDraft.value = true;
  try {
    //content文件
    file_content = await getFile({
      directory: workflowStore.getDraftDirectory,
      fileName: fileName_content,
      readType: 'Stream'
    });
    if (!file_content) {
      message.error(`未读取到草稿文件${fileName_content}`);
      loadingCreateDraft.value = false;
      return;
    }
    //meta文件
    file_meta = await getFile({
      directory: workflowStore.getDraftDirectory,
      fileName: fileName_meta,
      readType: 'Stream'
    });
    if (!file_meta) {
      message.error(`未读取到草稿文件${fileName_meta}`);
      loadingCreateDraft.value = false;
      return;
    }
  } catch (err) {
    message.error('读取草稿文件失败');
    loadingCreateDraft.value = false;
    return;
  }

  let data: createDraftReq = {
    product_title: currContent.value.product_title,
    product_id: currContent.value.product_id!,
    product_name: currContent.value.product_name,
    product_core: currContent.value.is_sell_point_override
      ? currContent.value.sell_point_override!
      : currContent.value.sell_point!,
    video_copywriting: currContent.value.is_deepAi_override
      ? currContent.value.sell_copy_override ?? ''
      : currContent.value.sell_copy ?? '',
    video: [],
    local_draft_url: workflowStore.getDraftDirectory,
    content_stream: file_content.toString(),
    meta_stream: file_meta.toString(),
    task_detailId: currContent.value.task?.id ?? 0
  };

  for (const video_material of currContent.value.video_materials) {
    try {
      const videoMeta: VideoInfo = await getVideoMeta(video_material);
      if (videoMeta)
        data.video.push({
          video_localUrl: video_material,
          width: videoMeta.width,
          height: videoMeta.height,
          duration: Math.round(videoMeta.duration * 1000000)
        });
    } catch (err) {
      message.error(video_material);
      message.error(`[素材路径]{${video_material}}读取视频文件信息失败`);
      loadingCreateDraft.value = false;
      return;
    }
  }
  const content = {...currContent.value};
  createDraftApi(data)
    .then(async (res) => {
      message.success('创建生产草稿成功！');
      workflowStore.setContentAction({
        ...content,
        draft_id: res.draft_id,
        stepwise: [...content.stepwise!, 4]
      });
      await writeFile(draftDirectoryProduction.value, fileName_meta, res.draft_meta);
      await writeFile(draftDirectoryProduction.value, fileName_content, res.draft_content);
    })
    .finally(() => {
      loadingCreateDraft.value = false;
      setTimeout(() => {
        workflowStore.setContentAction({
          ...content,
          disabledUseMoFang: false
        });
      }, 10000);
    });
};

//创意魔方
const handleCreativeMoFang = async () => {
  loadingCreativeMoFang.value = true;
  let file_content;
  try {
    file_content = await getFile({
      directory: draftDirectoryProduction.value,
      fileName: fileName_content,
      readType: 'Stream'
    });
    if (!file_content) {
      message.error(`未读取到生产草稿文件${fileName_content}`);
      loadingCreativeMoFang.value = false;
      return;
    }
  } catch (err) {
    message.error('读取生产草稿文件失败');
    loadingCreativeMoFang.value = false;
    return;
  }

  creativeMoFangApi({
    content_stream: file_content.toString(),
    draft_id: currContent.value.draft_id ?? 0
  })
    .then(async (res) => {
      message.success('创意魔方处理完成');
      workflowStore.setContentAction({
        ...currContent.value,
        stepwise: [...currContent.value.stepwise!, 5]
      });
      await writeFile(draftDirectoryProduction.value, fileName_content, res.content_stream);
    })
    .finally(() => {
      loadingCreativeMoFang.value = false;
    });
};

const handleOperation = (
  input: WorkflowInputProperties,
  indexIndex: number,
  menu: WorkflowMenuItemProperties,
  menuIndex: number
) => {
  if (input.operation == 'Copy') {
    if (copyTextToClipboard(input.content)) {
      message.success('内容已复制到剪贴板');
      menuItem[menuIndex].inputArray[indexIndex].copyState = true;
    } else {
      message.error('复制失败，请重试');
    }
  }
  if (input.operation == 'Refresh') {
    // 刷新文案
    productSellcopyRefreshApi({ product_id: currContent.value.product_id! }).then((res) => {
      if (res) {
        message.success('文案刷新中');
        currContent.value.sell_copy = undefined;
      } else message.error('文案刷新失败');
    });
  }
  if (input.operation == 'DouYin') {
    if (copyTextToClipboard(currContent.value.product_name ?? '')) {
      message.success('商品名称已复制到剪贴板');
    }
    setTimeout(() => {
      if (workflowStore.getMaterialDirectory)
        window.clientAppSdk.shell.openExternal(workflowStore.getMaterialDirectory);
      window.clientAppSdk.shell.openExternal(
        'https://www.douyin.com/root/search/' + currContent.value.product_name
      );
    }, 300);
  }
  if (input.operation == 'TaoBao') {
    window.clientAppSdk.shell.openExternal(currContent.value.task!.item_url);
  }
};

const menuItem = reactiveComputed<WorkflowMenuItemProperties[]>(() => {
  return [
    {
      icon: ProductTitle,
      title: '商品标题',
      inputArray: [
        {
          elementType: 'Textarea',
          content: currContent.value.product_title,
          height: 50,
          operation: currContent.value.task?.item_url ? 'TaoBao' : undefined,
          placeholder: currContent.value.task ? '' : '输入标题后按下Ctrl+Enter获取下列信息'
        }
      ]
    },
    {
      icon: ProductName,
      title: '商品名称',
      status: currContent.value.product_id
        ? currContent.value.error_message && !currContent.value.product_name
          ? 'Error'
          : currContent.value.stepwise?.some((x) => x == 2)
            ? 'Success'
            : 'Loading'
        : undefined,
      message: currContent.value.error_message,
      inputArray: [
        {
          elementType: 'Input',
          content: currContent.value.product_name ?? '',
          readonly: currContent.value.id == '',
        }
      ]
    },
    {
      icon: currContent.value.is_sell_point_override ? SellPointCoreOverride : SellPointCore,
      title: '核心卖点',
      status: currContent.value.error_message && !currContent.value.sell_point
        ? 'Error'
        : currContent.value.product_id && !currContent.value.is_sell_point_override
          ? currContent.value.stepwise?.some((x) => x == 2)
            ? 'Success'
            : 'Loading'
          : undefined,
      message: currContent.value.error_message,
      inputArray: [
        {
          elementType: 'Input',
          readonly: currContent.value.id == '',
          content:
            (currContent.value.is_sell_point_override
              ? currContent.value.sell_point_override
              : currContent.value.sell_point) ?? ''
        }
      ],
      click: () =>
        workflowStore.setContentAction({
          ...currContent.value,
          is_sell_point_override: !currContent.value.is_sell_point_override
        })
    },
    {
      icon: currContent.value.is_deepAi_override ? VideoTextOverride : VideoText,
      title: '视频文案',
      status: currContent.value.deepAi_error_message && currContent.value.open_deepAi &&
      !currContent.value.is_deepAi_override && !currContent.value.sell_copy
        ? 'Error'
        : currContent.value.product_id &&
            currContent.value.open_deepAi &&
            !currContent.value.is_deepAi_override
          ? currContent.value.stepwise?.some((x) => x == 3)
            ? undefined
            : 'Loading'
          : undefined,
      message: currContent.value.deepAi_error_message,
      inputArray: [
        {
          elementType: 'Textarea',
          content:
            (currContent.value.is_deepAi_override
              ? currContent.value.sell_copy_override
              : currContent.value.sell_copy) ?? '',
          height: 92,
          readonly: currContent.value.id == '',
          operation:
            !currContent.value.is_deepAi_override &&
            currContent.value.open_deepAi &&
            currContent.value.stepwise?.some((x) => x == 3)
              ? 'Refresh'
              : undefined
        }
      ],
      click: () =>
      {
        if(!currContent.value.open_deepAi) {
          message.info('人员账号未开启深度AI请求');
          return;
        }
        workflowStore.setContentAction({
          ...currContent.value,
          is_deepAi_override: !currContent.value.is_deepAi_override
        })
      }
    },
    {
      icon: currContent.value.is_deepAi_override ? VideoNameOverride : VideoName,
      title: '视频名称',
      status: currContent.value.deepAi_error_message && currContent.value.open_deepAi &&
      !currContent.value.is_deepAi_override
        ? 'Error'
        : currContent.value.product_id &&
            currContent.value.open_deepAi &&
            !currContent.value.is_deepAi_override
          ? currContent.value.stepwise?.some((x) => x == 3)
            ? undefined
            : 'Loading'
          : undefined,
      message: currContent.value.deepAi_error_message,
      inputArray: (() => {
        let videoNames = currContent.value.is_deepAi_override
          ? (currContent.value.video_names_override ??
            (currContent.value.video_names_override = new Array(5).fill('')))
          : currContent.value.video_names;

        return videoNames.map<WorkflowInputProperties>((name) => ({
          elementType: 'Input',
          content: name,
          operation: name ? 'Copy' : undefined,
          readonly: currContent.value.id == ''
        }));
      })(),
      click: () =>
      {
        if(!currContent.value.open_deepAi) {
          message.info('人员账号未开启深度AI请求');
          return;
        }
        workflowStore.setContentAction({
          ...currContent.value,
          is_deepAi_override: !currContent.value.is_deepAi_override
        })
      }
    },
    {
      icon: VideoMaterail,
      title: '视频素材',
      noticeNum: currContent.value.video_materials?.length ?? 0,
      inputArray: [
        {
          elementType: 'Input',
          content: currContent.value.video_materials?.toString() || '',
          placeholder: '点击选择多个视频素材',
          readonly: true,
          operation: currContent.value.product_name ? 'DouYin' : undefined
        }
      ]
    },
    {
      icon: Video,
      title: '发布流',
      isChief: true,
      inputArray: [
        {
          elementType: null,
          content: ''
        }
      ],
      click: () => {
        router.push({ name: 'DaRen' });
      }
    }
  ];
});
</script>
